<?php

namespace app\model;

use think\Model;

class UserLog extends Model
{
    // 表名
    protected $name = 'user_logs';

    // 自动时间戳
    protected $autoWriteTimestamp = 'datetime';

    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = false; // 日志不需要更新时间

    // 字段类型转换
    protected $type = [
        'extra_data' => 'json',
        'created_at' => 'datetime',
    ];

    // 关联用户
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // 记录日志
    public static function record($userId, $action, $description = '', $targetType = null, $targetId = null, $extraData = null)
    {
        $request = request();

        return self::create([
            'user_id' => $userId,
            'action' => $action,
            'target_type' => $targetType,
            'target_id' => $targetId,
            'description' => $description,
            'ip' => $request->ip(),
            'platform' => $request->param('platform', 'unknown'),
            'device_id' => $request->param('device_id'),
            'user_agent' => $request->header('user-agent'),
            'extra_data' => $extraData,
        ]);
    }

    // 获取用户日志
    public static function getUserLogs($userId, $limit = 50, $action = null)
    {
        $query = self::where('user_id', $userId);

        if ($action) {
            $query->where('action', $action);
        }

        return $query->order('created_at', 'desc')
            ->limit($limit)
            ->select();
    }

    // 获取操作类型中文名
    public function getActionNameAttr()
    {
        $actions = [
            'login' => '登录',
            'logout' => '退出',
            'register' => '注册',
            'bind_oauth' => '绑定第三方账号',
            'unbind_oauth' => '解绑第三方账号',
            'create_account' => '创建账号',
            'update_account' => '更新账号',
            'delete_account' => '删除账号',
            'view_account' => '查看账号',
            'copy_password' => '复制密码',
            'create_category' => '创建分类',
            'update_category' => '更新分类',
            'delete_category' => '删除分类',
            'change_password' => '修改密码',
            'update_profile' => '更新资料',
            'backup_data' => '备份数据',
            'restore_data' => '恢复数据',
            'export_data' => '导出数据',
            'import_data' => '导入数据',
        ];

        return $actions[$this->action] ?? $this->action;
    }

    // 清理旧日志
    public static function cleanup($days = 90)
    {
        $cutoffTime = date('Y-m-d H:i:s', time() - $days * 24 * 3600);
        return self::where('created_at', '<', $cutoffTime)->delete();
    }

    // 获取用户活跃统计
    public static function getUserActiveStats($userId, $days = 30)
    {
        $startTime = date('Y-m-d', time() - $days * 24 * 3600);

        return self::where('user_id', $userId)
            ->where('created_at', '>=', $startTime)
            ->field('DATE(created_at) as date, COUNT(*) as count')
            ->group('DATE(created_at)')
            ->order('date', 'asc')
            ->select();
    }

    // 获取最近登录记录
    public static function getRecentLogins($userId, $limit = 10)
    {
        return self::where('user_id', $userId)
            ->where('action', 'login')
            ->order('created_at', 'desc')
            ->limit($limit)
            ->select();
    }
}